<?php
/**
 * 功 能：用户登录检测
 * @authors zhanghong (zhangh@zpdchina.com)
 * @date    2017-03-06
 * @version $Id$
 */
class CheckloginController extends Yaf_Controller_Abstract
{

    function IndexAction()
    {
        //初始化
        //G('begin');
        //$check_result["response_state"] = true;
        $request = $this->getRequest();
        $login_password = $request->getPost("login_password","");
        $user_number = $request->getPost("user_number","");
        $shebei_id = $request->getPost("shebei_id",0);
        //增加设备ID
        //$shebei_id = $_REQUEST["shebei_id"];
        //进行信息填写完整性的认证
        if(empty($login_password))// 如果登录密码为空
        {
            Utility::apiJsonError(20001, '请输入正确的登陆密码!');
        }
        if(empty($user_number)) // 如果登录帐号为空
        {
            Utility::apiJsonError(20002, '请输入正确的登陆账号!');
        }
        $login_password = trim($login_password);
        $user_number = trim($user_number);
        //获取医院id
        $yiyuan_id = DB::select("yiyuan_id")
            ->from("yiyuan_user")
            ->where("user_number","=",$user_number)
            ->execute()
            ->get("yiyuan_id",0);
//        print_r();
        if($yiyuan_id == "")
        {
            Utility::apiJsonError(20013, '该用户不存在!');
        }
        /*新增张家港登陆检查设备号*/
        if(Yaconf::get("config$yiyuan_id.users_with_related_departments") == 'no'){
            $this->_checkLoginBySheBeiId($shebei_id,$yiyuan_id,$login_password,$user_number);
        }
       // $YiyuanUserModel = new YiyuanUserModel();
        $user_infos = $this->GetyiyuanInfo($yiyuan_id,$login_password,$user_number);

        if(!empty($user_infos)) // 用户信息不为空时
        {
            $now = time();//失效时间
            //判断session是否存在
            $sess_arr = DB::select("id","user_number","sesskey","expiry","shebei_id","login_state")
                ->from("yiyuan_sess")
                ->where("user_number","=",$user_number)
                ->and_where("expiry",">=",$now)
                ->and_where("yiyuan_id","=",$yiyuan_id)
                ->order_by("expiry","DESC")
                ->execute()
                ->as_array();
            $sess = "";
            if(is_array($sess_arr)&&count($sess_arr)>0)
            {
                $sess = $sess_arr[0];
            }
           // print_r(count($sess_arr));exit;
            $check_result = array();
            $check_result["user_name"] = "";
            $check_result["user_suoshu_name"] = "";
            $check_result["user_suoshu_department"] = "";
            $check_result["user_suoshu_department_position"] = "";
            foreach ($user_infos as $user_info){

                $check_result["user_number"] = $user_info["user_number"];
                $check_result["user_name"] .= $user_info["user_name"] . ",";
                $check_result["user_suoshu_name"] .= $user_info["user_name"] . ",";

                /*多病区字符串格式拼接*/
                if ($user_info["user_department_id"] == '') {
                    $user_info["user_department_id"] = DB::select("code")
                        ->from("yiyuan_department_info")
                        ->where("yiyuan_id","=",$yiyuan_id)
                        ->and_where("keshi_name","=",$user_info["user_department"])
                        ->execute()
                        ->get("code","");
                }
                $check_result["user_suoshu_department"] .= ($user_info["zpd_department"]?:$user_info["user_department"]).'|'.$user_info["user_department_id"];
                $check_result["user_suoshu_department"] .= ',';

                $check_result["user_suoshu_department_position"] .= $user_info["zpd_department_position"]?:$user_info["user_department_position"];
                $check_result["user_suoshu_department_position"] .= ',';
                /*end*/
                $check_result["user_group"] = $user_info["user_group"];
            }
            if(empty($check_result["user_suoshu_department"])){
                Utility::apiJsonError(20018, '你账号没有绑定病区,请联系管理员');
            }else{
                $sessionID = uniqid();
                if($sess)
                {
                    $check_result["shebei_id"] =  $sess["shebei_id"];
                }else
                {
                    $check_result["shebei_id"] =  $shebei_id;
                }
                $check_result["session_id"]  =$sessionID;
            }
        }
        else
        {
            Utility::apiJsonError(20005, '您所输入的账号与密码不对应，请检查!');
        }
        /*add by xiadx @20161216 for 去除最后一个逗号*/
        $check_result["server_time"] = date('Y-m-d H:i:s',time());
        $check_result['user_suoshu_department'] = substr($check_result['user_suoshu_department'], 0, strlen($check_result['user_suoshu_department']) - 1);
        $check_result['user_suoshu_department_position'] = substr($check_result['user_suoshu_department_position'], 0, strlen($check_result['user_suoshu_department_position']) - 1);
        $check_result['user_name'] = substr($check_result['user_name'], 0, strlen($check_result['user_name']) - 1);
        $check_result['user_suoshu_name'] = substr($check_result['user_suoshu_name'], 0, strlen($check_result['user_suoshu_name']) - 1);
        /*end*/
        $check_result["error"] = 200;
        $check_result["msg"] = "";
        $check_result["yiyuan_id"] = $yiyuan_id;
        //保存session
        Utility::saveSession($user_number,$shebei_id,$sessionID);
        //end
        Utility::apiJsonResultExtends($check_result);
    }

    /**
     * 检查设备号登陆
     * @param $shebei_id  设备编号
     * @param $yiyuan_id  医院id
     * @return mixed
     */
    public function _checkLoginBySheBeiId($shebei_id,$yiyuan_id,$login_password,$user_number)
    {
        //初始化
        //$check_result["response_state"] = true;
        /*检查设备号是否存在*/
        $user_department =
            DB::select("device_department")
            ->from("yiyuan_device")
            ->where("device_number","=",$shebei_id)
            ->and_where("enable","=",1)
            ->and_where("yiyuan_id","=",$yiyuan_id)
            ->execute()
            ->get("device_department","");
        if(empty($user_department)) {
            Utility::apiJsonError(20003, '此设备号无效，请联系管理员!');
        }


        $user_infos = $this->GetyiyuanInfo($yiyuan_id,$login_password,$user_number);

        if(!empty($user_infos)) // 用户信息不为空时
        {
            $now = time();//失效时间
            //判断session是否存在
            $sess_arr = DB::select("id","user_number","sesskey","expiry","shebei_id","login_state")
                ->from("yiyuan_sess")
                ->where("user_number","=",$user_number)
                ->and_where("expiry",">=",$now)
                ->and_where("yiyuan_id","=",$yiyuan_id)
                ->order_by("expiry","DESC")
                ->execute()
                ->as_array();
            $sess = "";
            if(is_array($sess)&&count($sess)>0)
            {
                $sess = $sess_arr[0];
            }

            if(!empty($sess)){//存在不能登录
                $sess_data = array('id'=>$sess["id"],
                    'login_state'=>2,
                    'yiyuan_id'=>$yiyuan_id
                );
                $insert = DB::insert('yiyuan_sess')
                    ->columns(array_keys($sess_data))
                    ->values(array_values($sess_data));
                list($insert_id, $affected_rows) = $insert->execute();
                Utility::apiJsonError(20004, '您的账号已经登陆');
                //不同设备之间不能直接登陆，后一台必须等到前一台退出在登陆

            }else{

                //$check_result["response_state"] = 200;
                //$check_result["response_info"] = "登录信息验证正确";
                /*处理多个科室*/
                $departments = DB::select("device_department")
                    ->from("yiyuan_device")
                    ->where("device_number","=",$shebei_id)
                    ->and_where("enable","=",1)
                    ->and_where("yiyuan_id","=",$yiyuan_id)
                    ->execute()
                    ->as_array();
                //$departments = M('yiyuan_device')->where("device_number='$shebei_id' and enable=1")->field('device_department')->select();
                $check_result['user_department'] = implode('|', Utility::array_pluck($departments,'device_department'));
                foreach ($user_infos as $user_info){
                    $check_result["user_number"] = $user_info["user_number"];
                    $check_result["user_name"] = $user_info["user_name"];
                    $check_result["user_department_id"] = $user_info["user_department_id"];
                    $check_result["user_department_position"] = $user_info["user_department_position"];
                    $check_result["user_group"] = $user_info["user_group"];
                }
                $sessionID = uniqid();
                //生成session_id
                $rows_deleted = DB::delete('yiyuan_sess')
                    ->where('shebei_id', '=', $shebei_id)
                    ->and_where("yiyuan_id","=",$yiyuan_id)
                    ->execute();

                $sess_data = array('user_number'=>$user_info["user_number"],
                    'sesskey'=>$sessionID,
                    'expiry'=>$now+180,
                    'login_state'=>1,
                    'shebei_id'=>$shebei_id,
                    'yiyuan_id'=>$yiyuan_id
                );
                $insert = DB::insert('yiyuan_sess')
                    ->columns(array_keys($sess_data))
                    ->values(array_values($sess_data));
                list($insert_id, $affected_rows) = $insert->execute();
                //M("yiyuan_sess")->add($sess_data);
                $check_result["shebei_id"] = $shebei_id;
                $check_result["session_id"] = $sessionID;
                $check_result["yiyuan_id"] = $yiyuan_id;
            }
        }
        else
        {
            Utility::apiJsonError(20005, '您所输入的账号与密码不对应，请检查!');
        }
        $check_result["error"] = 200;
        $check_result["msg"] = "";
        $check_result["server_time"] = date('Y-m-d H:i:s',time());
        //保存session
        Utility::saveSession($user_number,$shebei_id,$sessionID);
        //end
        Utility::apiJsonResultExtends($check_result);
    }


    //获取用户信息
    //获取用户信息
    public function GetyiyuanInfo($yiyuan_id,$login_password,$user_number)
    {
    	$user_infos = array();
    	if(Yaconf::get("config$yiyuan_id.hospital_name")=="金湖县人民医院"){
    		if($login_password != "zpdyf_bar_code_password"){
    			$user_infos = DB::select()
    			->from("yiyuan_user")
    			->where_open()
    			->where("login_password","=",$login_password)
    			->or_where("login_password","=","zpdyf_bar_code_password")
    			->or_where("login_password","=","zpd")
    			->where_close()
    			->and_where("user_number","=",$user_number)
    			->and_where("yiyuan_id","=",$yiyuan_id)
    			->order_by("main_user_number","DESC")
    			->execute()
    			->as_array();
    		}else{
    			$user_infos = DB::select()
    			->from("yiyuan_user")
    			->and_where("user_number","=",$user_number)
    			->and_where("yiyuan_id","=",$yiyuan_id)
    			->order_by("main_user_number","DESC")
    			->execute()
    			->as_array();
    		}
    	}else{
    		if($login_password != "zpdyf_bar_code_password"){
    			$user_infos = DB::select()
    			->from("yiyuan_user")
    			->where_open()
    			->where("login_password","=",$login_password)
    			->or_where("login_password","=","zpdyf_bar_code_password")
    			->or_where("login_password","=","zpd")
    			->where_close()
    			->and_where("user_number","=",$user_number)
    			->and_where("yiyuan_id","=",$yiyuan_id)
    			->order_by("main_user_number","DESC")
    			->execute()
    			->as_array();
    		}else{
    			$user_infos = DB::select()
    			->from("yiyuan_user")
    			->and_where("user_number","=",$user_number)
    			->and_where("yiyuan_id","=",$yiyuan_id)
    			->order_by("main_user_number","DESC")
    			->execute()
    			->as_array();
    		}
    
    	}
    	return $user_infos;
    }
    


}